package com.travel.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.JwtUtils;
import com.travel.RsaUtils;
import com.travel.entity.dto.ResultVO;
import com.travel.sso.TravelUser;
import com.travel.user.mapper.TravelUserMapper;
import com.travel.user.service.ITravelUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author muzi
 * @since 2021-04-15
 */
@Service
public class TravelUserServiceImpl extends ServiceImpl<TravelUserMapper, TravelUser> implements ITravelUserService {

    @Override
    public ResultVO<TravelUser> login(TravelUser travelUser) {
        //根据username获取user信息
        QueryWrapper<TravelUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",travelUser.getUserAccount());
        TravelUser travelUser1 = this.baseMapper.selectOne(queryWrapper);

        if(travelUser1==null){
            return new ResultVO(false,"用户名或者密码错误");
        }

        BCryptPasswordEncoder encoder= new BCryptPasswordEncoder();
        if(!encoder.matches(travelUser.getUserPassword(),travelUser1.getUserPassword())){
            return  new ResultVO(false,"用户名或者密码错误");
        }

        //获取私钥
        PrivateKey privateKey=null;
        try {
            privateKey= RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa").getPath());
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        //颁发令牌
        travelUser1.setUserPassword(null);
        String token = JwtUtils.generateTokenExpireInMinutes(travelUser1, privateKey, 30);


        return new ResultVO(true,"success",token);
    }
}
